<script setup>
import { nextTick, onMounted, ref } from "vue";
import { useUserStore, useStuDataStore } from "@/store";
import {
  delectImgItem,
  postAdminAbsence,
  postAdminCompetition,
  postImgItem,
  postPaperAdmin,
} from "@/api/home/adminIndex.js";

import { postCarousel, postStuHome } from "@/api/home/stuIndex.js";

import AdminHome from "@/components/Echarts/adminHome.vue";
import StuHome from "../../components/Echarts/stuHome.vue";
import { ElMessage } from "element-plus";

import { getNotifications } from "@/api/account.js";

const userStore = useUserStore();

let cardForm = ref({
  CA_approve1: null,
  CA_approve2: null,
  PP_approve1: null,
  PP_approve2: null,
  LV_approve1: null,
  LV_approve2: null,
});

const getCardForm = async () => {
  const [ca0, ca4, pp0, pp4, lv0, lv3] = await Promise.all([
    postAdminCompetition(0),
    postAdminCompetition(4),
    postPaperAdmin(0),
    postPaperAdmin(4),
    postAdminAbsence(0),
    postAdminAbsence(3),
  ]);
  cardForm.value = {
    CA_approve1: ca0.count,
    CA_approve2: ca4.count,
    PP_approve1: pp0.count,
    PP_approve2: pp4.count,
    LV_approve1: lv0.count,
    LV_approve2: lv3.count,
  };
};

const statsColr = ["#67C23A", "#F56C6C"];

const imgList = ref([]);
const getImgList = async () => {
  const res = await postCarousel();
  if (res.code) {
    ElMessage.error("获取轮播图失败");
    return;
  }

  // console.log("img", res.data);
  imgList.value = res.data;
};

let diaVisable1 = ref(false);
let formRef = ref(null);
let applyForm = ref({
  topic: "",
  toUrl: "",
  img: "",
});
let imgUrl = ref(); //回显url
let urlList = ref([]); //预览图片用

const postApply = async () => {
  const res = await postImgItem(applyForm.value);
  if (res.code) {
    ElMessage.error("上传失败");
    return;
  }

  // console.log("img", res.data);
  imgList.value = res.data;
  await handleClose_applyForm();
};

const uploadImg = async (item) => {
  urlList.value = []; //先置空
  applyForm.value.img = item.raw; //图片文件本体
  imgUrl.value = URL.createObjectURL(item.raw); //回显用
  // console.log("图片url：", imgUrl)
  urlList.value.push(imgUrl.value);
};

const imgFormat = (rawFile) => {
  console.log("111");
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("请上传图片格式!");
    return false;
  }
  return true;
};

// 重置applyForm
const handleReset_apply = () => {
  console.log("重置");
  applyForm.value = {
    topic: "",
    toUrl: "",
    img: "",
  };
  imgUrl.value = null; //图片url缓存
  urlList.value = []; //图片回显list
};

const handleClose_applyForm = async () => {
  handleReset_apply(); //清除form内容
  diaVisable1.value = false;
  await nextTick(() => {
    formRef.value.clearValidate();
  });
};

let applyForm_rules = ref({
  topic: [
    {
      required: true,
      message: "请输入轮播标题",
      trigger: "blur",
    },
  ],
  toUrl: [
    {
      required: true,
      message: "请输入跳转地址",
      trigger: "blur",
    },
  ],
  img: [
    {
      required: true,
      message: "请上传图片",
      trigger: "blur",
    },
  ],
});

let carouselId = ref();
const onCarouselChange = (index) => {
  carouselId.value = imgList.value[index].id;
};

const delectCarouselById = async () => {
  const res = await delectImgItem(carouselId.value);
  if (res.code) {
    ElMessage.error("获取轮播图失败");
    return;
  }
  ElMessage.success("删除成功");
  console.log("img", res.data);
  imgList.value = res.data;
};

//学生的通知
const total = ref(0);
const pagenum = ref(1); //页数
const pagesize = ref(3);

const notesList = ref([]);
const getNotesList = async () => {
  const res = await getNotifications(pagenum.value, pagesize.value);
  if (res.code) {
    ElMessage.error("获取通知失败");
    return;
  }
  ElMessage.success("获取成功");
  console.log("notelist", res);
  total.value = res.data.total;
  notesList.value = res.data.notifications;
};

const StuDataStore = useStuDataStore();

// const stuDataForm = ref({
//   cognizanceVO: { national: 0, provincial: 0, school: 0 },
//   paperVO: {
//     software: 0,
//     patent: 0,
//     paper: 0,
//   },
//   leaveVO: { leaving: 0, overnightStay: 0, verifiedReturn: 0 },
// });

const getStuData = async () => {
  const res = await postStuHome();
  if (res.code) {
    ElMessage.error("获取学生数据失败");
    return;
  }
  ElMessage.success("获取学生数据成功");
  StuDataStore.stuDataForm = res.data;
  console.log("stuData", res.data);
  console.log("StuDataStore", StuDataStore.stuDataForm);
  // StuDataStore.setStuData(res.data);
  // console.log("StuDataStore2",StuDataStore.stuDataForm)
};

onMounted(() => {
  getCardForm();
  getImgList();
  getNotesList();
  if (!userStore.userRole.includes("ROLE_ADMIN")) getStuData();
});
</script>
<template>
  <!--  admin状态下-->
  <div v-if="userStore.userRole.includes('ROLE_ADMIN')">
    <el-card style="margin-bottom: 20px">
      <!-- //展示用户个人信息，从userStore中获取 -->
      <!-- //用表单展示 -->
      <div class="box1">
        <div class="proInfo">
          <el-form label-width="80px">
            <el-form-item label="姓名">
              <span>{{ userStore.username }}</span>
            </el-form-item>
            <el-form-item label="性别">
              <span>{{ userStore.userVO.userGender }}</span>
            </el-form-item>
            <el-form-item label="部门">
              <span>{{ userStore.userVO.userDep }}</span>
            </el-form-item>
          </el-form>
          <el-row>
            <el-col :span="12">
              <el-button @click="diaVisable1 = true" text plain type="success"
                >新增轮播图</el-button
              >
            </el-col>
            <el-col :span="12">
              <el-button @click="delectCarouselById" text plain type="warning"
                >删除轮播图</el-button
              >
            </el-col>
          </el-row>
        </div>
        <div class="imgbox">
          <el-carousel
            :interval="2000"
            type="card"
            height="200px"
            @change="onCarouselChange"
            loop
          >
            <el-carousel-item v-for="item in imgList" :key="item.id">
              <!-- <h3 text="2xl" justify="center">{{ item }}</h3> -->
              <a :href="item.toUrl" target="_blank">
                <img :src="item.imgUrl" alt="" class="imglist" />
              </a>
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
    </el-card>
    <el-card style="margin-bottom: 20px">
      <h2>系统通知</h2>
      <el-table :data="notesList" height="160px" style="font-size: 15px">
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column prop="status" width="80"
          ><template #default="scope">
            <span
              :style="{
                color: scope.row.status == '已读' ? '#409EFF' : '#F56C6C',
              }"
              >{{ scope.row.status }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="content" width="800">
          <!-- //怎么指定列内字体的颜色 -->
          <template #default="scope">
            <span
              :style="{
                color: scope.row.status == '已读' ? '#737478' : '#409EFF',
              }"
              >{{ scope.row.content }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="createdTime"></el-table-column>
      </el-table>
      <el-pagination
        @current-change="getNotesList"
        size="small"
        layout="prev, pager, next"
        :total="total"
        :page-size="3"
        :pager-count="5"
        v-model:current-page="pagenum"
      />
    </el-card>
    <el-row :gutter="20" style="margin-bottom: 8px">
      <el-col :span="8">
        <!--      竞赛报备-->
        <el-card>
          <el-row>
            <el-col :span="8">
              <p class="box_title">竞赛报备</p>
            </el-col>
            <el-col :span="16">
              <el-col
                >待审核
                <span
                  :style="{
                    color: cardForm.CA_approve1 ? statsColr[1] : statsColr[0],
                  }"
                >
                  {{ cardForm.CA_approve1 }}</span
                >项</el-col
              >
              <br />
              <el-col
                >待认定
                <span
                  :style="{
                    color: cardForm.CA_approve2 ? statsColr[1] : statsColr[0],
                  }"
                >
                  {{ cardForm.CA_approve2 }}</span
                >项</el-col
              >
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="8">
        <!--      论文专利软著-->
        <el-card>
          <el-row>
            <el-col :span="8">
              <p class="box_title">论文专利软著</p>
            </el-col>
            <el-col :span="16">
              <el-col
                >待审核
                <span
                  :style="{
                    color: cardForm.PP_approve1 ? statsColr[1] : statsColr[0],
                  }"
                >
                  {{ cardForm.PP_approve1 }}</span
                >项</el-col
              >
              <br />
              <el-col
                >待认定
                <span
                  :style="{
                    color: cardForm.PP_approve2 ? statsColr[1] : statsColr[0],
                  }"
                >
                  {{ cardForm.PP_approve2 }}</span
                >项</el-col
              >
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="8">
        <!--      离校申请-->
        <el-card>
          <el-row>
            <el-col :span="8">
              <p class="box_title">离校申请</p>
            </el-col>
            <el-col :span="16">
              <el-col
                >待审核
                <span
                  :style="{
                    color: cardForm.LV_approve1 ? statsColr[1] : statsColr[0],
                  }"
                >
                  {{ cardForm.LV_approve1 }} </span
                >项</el-col
              >
              <br />
              <el-col
                >待核实
                <span
                  :style="{
                    color: cardForm.LV_approve2 ? statsColr[1] : statsColr[0],
                  }"
                >
                  {{ cardForm.LV_approve2 }}</span
                >项</el-col
              >
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <!--  数据饼图-->
    <el-card>
      <admin-home></admin-home>
    </el-card>
  </div>
  <div v-else>
    <el-card style="margin-bottom: 20px">
      <!-- //展示用户个人信息，从userStore中获取 -->
      <!-- //用表单展示 -->
      <div class="box1">
        <div class="proInfo">
          <el-form label-width="70px">
            <el-form-item label="姓名">
              <span>{{ userStore.username }}</span>
            </el-form-item>
            <el-form-item label="性别">
              <span>{{ userStore.userVO.userGender }}</span>
            </el-form-item>
            <el-form-item label="学号">
              <span>{{ userStore.uid }}</span>
            </el-form-item>
            <el-form-item label="班级">
              <span>{{ userStore.userVO.userDep }}</span>
            </el-form-item>
          </el-form>
        </div>
        <div class="imgbox">
          <el-carousel :interval="2000" type="card" height="200px" loop>
            <el-carousel-item v-for="item in imgList" :key="item.id">
              <!-- <h3 text="2xl" justify="center">{{ item }}</h3> -->
              <a :href="item.toUrl" target="_blank">
                <img :src="item.imgUrl" alt="" class="imglist" />
              </a>
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
    </el-card>
    <el-card style="margin-bottom: 20px">
      <h2>系统通知</h2>
      <el-table :data="notesList" height="160px" style="font-size: 15px">
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column prop="status" width="80"
          ><template #default="scope">
            <span
              :style="{
                color: scope.row.status == '已读' ? '#409EFF' : '#F56C6C',
              }"
              >{{ scope.row.status }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="content" width="800">
          <!-- //怎么指定列内字体的颜色 -->
          <template #default="scope">
            <span
              :style="{
                color: scope.row.status == '已读' ? '#737478' : '#409EFF',
              }"
              >{{ scope.row.content }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="createdTime"></el-table-column>
      </el-table>
      <el-pagination
        @current-change="getNotesList"
        size="small"
        layout="prev, pager, next"
        :total="total"
        :page-size="3"
        :pager-count="5"
        v-model:current-page="pagenum"
      />
    </el-card>
    <el-card>
      <stu-home></stu-home>
    </el-card>
  </div>

  <el-dialog v-model="diaVisable1" :before-close="handleClose_applyForm">
    <el-form ref="formRef" :model="applyForm" :rules="applyForm_rules">
      <el-form-item label="轮播图标题" prop="topic">
        <el-input v-model="applyForm.topic" />
      </el-form-item>
      <el-form-item label="跳转地址" prop="toUrl">
        <el-input v-model="applyForm.toUrl" />
      </el-form-item>
      <el-form-item label="轮播图片" prop="img">
        <el-upload
          class="avatar-uploader"
          action="#"
          :auto-upload="false"
          :multiple="false"
          :show-file-list="false"
          :on-change="uploadImg"
          :before-upload="imgFormat"
        >
          <el-icon v-if="applyForm.img == ''" class="avatar-uploader-icon"
            ><Plus
          /></el-icon>
          <el-image class="img_file" :fit="'fill'" :src="imgUrl" v-else />
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleReset_apply">重置</el-button>
        <el-button type="success" @click="postApply"> 提交 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style scoped lang="scss">
.box {
  display: flex;
  .text {
    padding: 20px;
    .title {
      font-size: 30px;
      font-weight: 900;
      //加粗程度
    }
    .desc {
      font-size: 26px;
      color: forestgreen;
      margin-top: 20px;
    }
  }
}

.box_title {
  font-weight: bold;
}

.box1 {
  width: 100%;
  height: 200px;
  display: flex;
  justify-content: space-between;
  .proInfo {
    width: 25%;
    margin-right: 20px;
  }
  .imgbox {
    width: 75%;
    margin-right: 20px;
    .imglist {
      width: 100%;
      height: 100%;
    }
  }

  .el-carousel__item h3 {
    color: #475669;
    opacity: 0.75;
    line-height: 150px;
    margin: 0;
    text-align: center;
  }

  .el-carousel__item:nth-child(2n) {
    background-color: #99a9bf;
  }

  .el-carousel__item:nth-child(2n + 1) {
    background-color: #d3dce6;
  }
}

.avatar-uploader .img_file {
  width: 180px;
  height: 120px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 180px;
  height: 120px;
  text-align: center;
}
</style>
